<?php
/**
*
* 功能描述（订单控制器）
*
* @author suoya <jlusuoya@gmail.com>
* @version 1
*/

class CtrlOrder extends CtrlBase
{
	public $paramCheck = array(
		"showlist" => array(
			'status' => array("GET", "0", "intval", "notnegative"),
			'type' => array("GET", "0", "intval", "notnegative"),
			'c_start' => array('GET', '', '', 'datetime'),
			'c_end' => array('GET', '', '', 'datetime'),
			'd_start' => array('GET', '', '', 'datetime'),
			'd_end' => array('GET', '', '', 'datetime'),
			'key' => array("GET", "", "trim", ""),
			'keyword' => array("GET", "", "trim", ""),
			"page" => array("GET", "1", "intval", "positive"),
		),
		'pay' => array(
			'id' => array("GET", "must", "intval", "positive"),
			'note' => array("POST", "must", "trim", "notempty"),
		),
		'payui' => array(
			'id' => array("GET", "must", "intval", "positive"),
		),
		'modpaytype' => array(
			'id' => array('GET', 'must', 'intval', 'positive'),
			'pay_type' => array('GET', 'must', 'intval', 'positive'),
		),
		'moddely' => array(
			'id' => array('GET', 'must', 'intval', 'positive'),
			'consignee' => array('POST', 'must', 'trim', 'notempty'),
			'mobile_to' => array('POST', 'must', 'trim', 'mobile'),
			'dely_type' => array('POST', 'must', 'intval', 'positive'),
			'dely_date' => array('POST', 'must', 'trim', 'date'),
			'dely_time' => array('POST', 'must', 'trim', 'timeslot'),
			'sign_build' => array('POST', 'must', 'trim', ''),
			'true_area' => array('POST', 'must', 'trim', 'notempty'),
			'address' => array('POST', 'must', 'trim', 'notempty'),
			'message' => array('POST', 'must', 'trim', 'notempty'),
		),
		'modamount' => array(
			'id' => array('GET', 'must', 'intval', 'positive'),
			'score' => array('POST', 'must', 'intval', 'notnegative'),
			'amount' => array('POST', 'must', 'floatval', 'notnegative'),
			'message' => array('POST', 'must', 'trim', 'notempty'),
		),
		"setstatus" => array(
			'id' => array("GET", "must", "intval", "positive"),
			'status' => array("GET", "must", "intval", "positive"),
		),
		"setspstatus" => array(
			'id' => array("GET", "must", "intval", "positive"),
			'type' => array("GET", "must", "intval", "positive"),
			'status' => array("GET", "must", "intval", "bool"),
		),
		"detail" => array(
			'id' => array("GET", "must", "intval", "positive"),
		),
		'commit' => array(
		),
		"create" => array(
			"order_type" => array("POST", "must", "intval", "positive"),
			"need_card_birthday" => array("POST", "0", "intval", "bool"),
			"card_birthday" => array("POST", "", "trim", ""),
			"need_card" => array("POST", "0", "intval", "bool"),
			"card_message" => array("POST", "", "trim", ""),
			"need_album" => array("POST", "0", "intval", "bool"),
			"need_candle" => array("POST", "0", "intval", "bool"),
			"true_area" => array("POST", "must", "trim", "notempty"),
			"address" => array("POST", "must", "trim", "notempty"),
			"consignee" => array("POST", "must", "trim", "notempty"),
			"zipcode" => array("POST", "0", "intval", "notnegative"),
			"mobile_to" => array("POST", "must", "trim", "mobile"),
			"mobile_from" => array("POST", "must", "trim", "mobile"),
			"sign_building" => array("POST", "", "trim", ""),
			"delivery_type" => array("POST", "must", "trim", "notempty"),
			"delivery_date" => array("POST", "must", "", "date"),
			"delivery_time" => array("POST", "must", "", "timeslot"),
			"payment" => array("POST", "must", "intval", "positive"),
			"card_pwd" => array("POST", "0", "intval", "notnegative"),	//代金
			"integral" => array("POST", "0", "intval", "notnegative"), //积分
			"need_inv" => array("POST", "0", "intval", "bool"),
			"inv_title" => array("POST", "", "trim", ""),
			"inv_type" => array("POST", "", "trim", ""),
			"message" => array("POST", "", "trim", ""),
			"cart" => array("SESSION", "must", "", ""),
			"order_set" => array("SESSION", "must", "", ""),
		),
	);

	public $perm = array('order', "index.php?action=login.tologin");

	private $ret_msg = array();

	function ShowList()
	{
		$type = $this->params['type'];
		$status = $this->params['status'];
		$key = $this->params['key'];
		$keyword = $this->params['keyword'];
		$c_start = $this->params['c_start'];
		$c_end = $this->params['c_end'];
		$d_start = $this->params['d_start'];
		$d_end = $this->params['d_end'];
		$where = "1";
		if($status != 0)
			$where .= " and status = $status";

		$obj = $this->GetModel("order");
		$data = $obj->GetList($this->params['page'], $where, $type, $c_start, $c_end,
			SlotFormt('beg', $d_start), SlotFormt('end', $d_end), $key, $keyword);
		$this->assign("listdata", $data['data']);
		$this->assign("totalCnt", $data['cnt']);
		$this->assign("pageCnt", $data['pageCnt']);
		$this->assign("curPage", $this->params['page']);
		$this->assign("status", $status);
		$this->assign("type", $type);
		$this->assign("key", $key);
		$this->assign("keyword", $keyword);
		$this->assign("c_start", $c_start);
		$this->assign("c_end", $c_end);
		$this->assign("d_start", $d_start);
		$this->assign("d_end", $d_end);
		return RT_TPL;
	}

	function ModPayType()
	{
		$obj = $this->GetModel("order");
		$p_type = $this->params['pay_type'];
		//{#$p_type=[ 1=>'余额支付', 2=>'货到付款', 3=>'支付宝在线支付', 4=>'银行转账', 11=>'月结(VIP会员)', 12=>'周结(VIP会员)', 21=>'赠送(内部专用)']#}
		if(!in_array($p_type, array(1, 2, 3, 4, 11, 12, 21)))
			return RT_ATTACK;
		$id = $this->params['id'];
		$mod_data = array('pay_type' => $p_type);
		$amount = -1;
		if($p_type == 1)
		{
			$odata = $obj->GetBaseInfo($id);
			if(!$odata)
				return RT_ATTACK;
			$amount = $odata['amount'];
			if($odata['pay_adm'] != 0)
			{
				echo '该订单已付款，如要修改请先取消';
				return RT_NONE;
			}
			$uobj = $this->GetModel("user");
			$udata = $uobj->GetAccInfo($odata['userid']);
			if($udata['money'] < $odata['amount'])
			{
				echo '余额不足，仅有'.$udata['money'];
				return RT_NONE;
			}
			if(!$uobj->DecMoney($odata['userid'],  $odata['amount']))
			{
				echo '扣款失败';
				return RT_NONE;
			}
			$mod_data['pay_adm'] = 1;
		}
		$cnt = $obj->UpdateOrder($mod_data, $this->params['id'], 'and pay_adm = 0');
		if($cnt > 0)
		{
			$this->CoreLog('order_modptype', $this->params['id'], 0, $amount);
			echo '0';
		}
		else
			echo '2';
		return RT_NONE;
	}

	function ModDely()
	{
		$id = $this->params['id'];
		$data = array (
			'consignee' => $this->params['consignee'],
			'mobile_to' => $this->params['mobile_to'],
			'delivery_type' => $this->params['dely_type'],
			'delivery_time' => $this->params['dely_date'] . ' ' . $this->params['dely_time'],
			'sign_building' => $this->params['sign_build'],
			'area' => $this->params['true_area'],
			'address' => $this->params['address'],
			'message' => $this->params['message'],
		);
		$obj = $this->GetModel("order");
		$cnt = $obj->UpdateOrder($data, $id, 'and status = 1');
		if($cnt <= 0)
			echo '2';
		else
		{
			echo '0';
			$this->CoreLog('order_moddely', $id, $cnt, $this->params['mobile_to'].'|'.$this->params['message']);
		}
		return RT_NONE;
	}

	function ModAmount()
	{
		$id = $this->params['id'];
		$score = $this->params['score'];
		$amount = $this->params['amount'];
		$msg = $this->params['message'];
		$data = array(
			'add_score' => $score,
			'amount' => $amount,
			'message' => $msg,
		);
		if($amount ==  0)
			$data['pay_adm'] = 1;
		$obj = $this->GetModel("order");
		$cnt = $obj->UpdateOrder($data, $id, 'and status = 1');
		if($cnt > 0)
		{
			$this->CoreLog('order_modamount', $id, $score, $amount.'|'.$msg);
			echo '0';
		}
		else
			echo '2';
		return RT_NONE;
	}

	function SetStatus()
	{
		$id = $this->params['id'];
		$sta = $this->params['status'];
		if($sta < 2 || $sta > 3)
			return RT_ATTACK;
		$data = array(
			'status' => $sta,
		);
		$obj = $this->GetModel("order");
		$msg = '';
		if($sta == 2)	//完成
		{
			$odata = $obj->GetBaseInfo($id);
			if(!$odata)
				return RT_ATTACK;
			if($odata['status'] != 1 || $odata['pay_adm'] == 0)
				return RT_ATTACK;
			if($odata['add_score'] != 0)
			{
				//添加积分
				$msg = '加积分'.$odata['add_score'];
				$uobj = $this->GetModel("user");
				if($uobj->IncScore($odata['userid'], $odata['add_score']) <= 0)
				{
					echo '添加积分失败';
					return RT_NONE;
				}
			}
			$cobj = $this->GetModel("cake");
			$cobj->IncSalesByOrder($id);
		}
		$cnt = $obj->UpdateOrder($data, $id, ' and status = 1');
		if($cnt == 0)
			echo "2";
		else
		{
			$this->CoreLog('order_sta', $id, $sta, $msg);
			echo "0";
		}
		return RT_NONE;
	}

	function SetSpStatus()
	{
		$id = $this->params['id'];
		$sta = $this->params['status'];
		$type = $this->params['type'];
		$k = '';
		switch($type)
		{
		case 1: $k = 'cofm'; break;
		case 2:
			$k = 'pay';
			if($sta != 0)
				return RT_ATTACK;
			break;
		default:
			return RT_ATTACK;
		}
		if($sta == 1)
			$sta = $this->user->userid;
		$data = array(
			$k."_adm" => $sta,
		);
		$obj = $this->GetModel("order");
		$cnt = $obj->UpdateOrder($data, $id, ' and status = 1');
		if($cnt == 0)
			echo "2";
		else
		{
			$msg = "";
			if($type == 1 && $sta != 0)	//通知生产
			{
				$data = $obj->GetBaseInfo($id);
				$this->DoConfim($id, $data['mobile_to'], $data['dely_type'], $data['dely_time'], '');
				$ret = intval($this->ret_msg['prod']);
				if(intval($this->ret_msg['prod']) <= 0)
					$msg .= "通知生产失败";
				$ret = intval($this->ret_msg['prod']);
				if(strval($this->ret_msg['dely']) != '' && intval($this->ret_msg['dely']) <= 0)
					$msg .= "通知配送失败";
				if($msg != '')
					echo $msg;
			}
			else
				echo "0";
			$this->CoreLog($k."_sta", $id, $sta, $msg);
		}
		return RT_NONE;
	}

	function Detail()
	{
		$obj = $this->GetModel("order");
		$id = $this->params['id'];
		$data = $obj->GetAllInfo($id);
		if(!$data)
		{
			$this->assign("msg", "订单不存在");
			return RT_MSG;
		}
		$this->assign("data", $data);
		$this->assign('dely_date', substr($data['delivery_time'], 0, 10));
		$this->assign('dely_time', substr($data['delivery_time'], 11));
		$goods = $obj->GetAllGoods($id);
		$this->assign("goods", $goods);
		return RT_TPL;

	}

	function PayUi()
	{
		$obj = $this->GetModel("order");
		$data = $obj->GetBaseInfo($this->params['id']);
		if(!$data)
			return RT_ATTACK;
		if($data['pay_adm'] != 0)
		{
			echo '订单已经付款';
			return RT_NONE;
		}
		$GLOBALS['order'] = $data;
		return RT_PHP;
	}

	function Commit()
	{
		if(array_key_exists("cart", $_SESSION))
			$this->assign("goods", $_SESSION['cart']);
		else
			$this->assign("goods", array());
		$_SESSION['order_set'] = time(0);
		$this->assign("g_sid", session_id());
		$this->assign("area_come", AREA_COME);
		$this->assign("addr_come", ADDR_COME);
		return RT_TPL;
	}

	function Create()
	{
		/*
		$this->assign('ret_msg', array(
			'mobile' => '18210283045',
			'order' => 103,
			'user' => array(0, 1),
			'prod' => 1,
			'dely' => 1,
			));
		return RT_TPL;
		 */
		if(time(0) - $_SESSION['order_set'] > 900)
		{
			$this->assign("msg", "操作超时，请在15分钟内确认订单");	//否则商品过期导致订单无效
			return RT_MSG;
		}
		unset($_SESSION['order_set']);
		//确认用户
		$mobile = $this->params['mobile_from'];
		$uobj = $this->GetModel("user");
		$user = $uobj->GetUser($mobile);
		$this->ret_msg['mobile'] = $mobile;
		$pwd = '';
		if(!$user)
		{
			$pwd = RandStr(8);
			$type = $this->params['order_type'];
			$id = $uobj->CreateUser($type, $mobile, $pwd);
			if($id <= 0)
			{
				$this->assign("msg", "创建用户失败");
				return RT_MSG;
			}
			$this->CoreLog('user_add', $id, 0, 'by order');
			$user = array('id' =>$id, 'type' => $type);
			//应该通知用户
			$this->ret_msg['user'] = array(0, $user['id']);
		}
		else
			$this->ret_msg['user'] = array(1, $user['id']);
		//计算总值
		$cart = $_SESSION['cart'];
		$cnt = 0;
		$amount = $this->GetAmount($cart, $cnt);
		if($cnt <= 0)
		{
			$this->assign("msg", "购物车商品已全部过期");
			return RT_MSG;
		}
		$data = array(
			'userid' => $user['id'],
			'type'=>$user['type'],
			'add_adm'=>$this->user->userid,
			'cofm_adm'=>$this->user->userid
		);
		if($this->params['need_card_birthday'] == 1)
			$data['card1'] = $this->params['card_birthday'];
		if($this->params['need_card'] == 1)
			$data['card2'] = $this->params['card_message'];
		if($this->params['need_album'] == 1)
			$data['attach1'] = 1;
		if($this->params['need_candle'] == 1)
			$data['attach2'] = 1;
		$data['area'] = $this->params['true_area'];
		$data['address'] = $this->params['address'];
		$data['consignee'] = $this->params['consignee'];
		$data['zipcode'] = $this->params['zipcode'];
		$data['mobile_to'] = $this->params['mobile_to'];
		$data['mobile_from'] = $this->params['mobile_from'];
		$data['sign_building'] = $this->params['sign_building'];
		$data['delivery_type'] = $this->params['delivery_type'];
		$dely_time = $this->params['delivery_date']. ' ' .$this->params['delivery_time'];
		$data['delivery_time'] = $dely_time;
		$data['pay_type'] = $this->params['payment'];
		$data['trade_money1'] = $this->params['card_pwd'];
		$data['trade_money2'] = $this->params['integral'];
		if($this->params['need_inv'] == 1)
		{
			$data['inv_title'] = $this->params['inv_title'];
			$data['inv_type'] = $this->params['inv_type'];
		}
		$data['message'] = $this->params['message'];


		$data['amount_pre'] = $amount;
		$data['amount'] = $amount - $data['trade_money2'] * 0.1; //mod after
		$obj = $this->GetModel("Order");
		$id = $obj->Create($data);
		if($id == 0)
		{
			$this->assign("msg", "创建订单失败");
			return RT_MSG;
		}
		$this->ret_msg['order'] = $id;
		$this->CoreLog('order_add', $id, $user['id'], '');
		$food = $obj->SaveData($id, $cart);
		if($food == 0)
		{
			$this->assign("msg", "存储订单失败");
			return RT_MSG;
		}
		unset($_SESSION['cart']);
		unset($_SESSION['bind']);
		$this->DoConfim($id, $this->params['mobile_to'], $this->params['delivery_type'], $dely_time, $pwd);
		$this->assign("ret_msg", $this->ret_msg);
		return RT_TPL;
	}

	function Pay()
	{
		$obj = $this->GetModel("order");
		$data = $obj->GetBaseInfo($this->params['id']);
		if(!$data || $data['status'] != 1)
			return RT_ATTACK;
		if($data['pay_adm'] != 0)
		{
			echo '订单已经付款';
			return RT_NONE;
		}
		$data = array(
			'status' => 2,
			'lasttime' => date("Y-m-d H:i:s"),
			'trade_type' => 2,
			'type' => $data['pay_type'],
			'amount' => $data['amount'],
			'data_id' => $data['id'],
			'user_id' => $data['userid'],
			'ret_status' => 'by adm',
			'order_id' => '',
			'info' => $this->params['note'],
		);
		$tobj = $this->GetModel("Trade");
		$id = $tobj->NewItem($data);
		if($id > 0)
		{
			$obj->UpdateOrder(array('pay_adm' => $this->user->userid), $this->params['id']);
			echo '0';
		}
		else
			echo '2';
		return RT_NONE;
	}

	private function DoConfim($id, $mobile_to, $delyType, $delyTime, $pwd )
	{
		$obj = $this->GetModel("Order");
		$this->ret_msg['prod'] = $obj->NoticeProd($id);
		if($delyType == 1)
			$this->ret_msg['dely'] = $obj->NoticeDely($id);
		else
			$this->ret_msg['dely'] = '';
		$this->SendMobileMsg($mobile_to, $id, $delyType, $delyTime, $pwd);
	}

	private function SendMobileMsg($mobile, $id, $delyType, $delyTime, $pwd)
	{
		//下属短信
		$id += ORDERBASE;
		$m_msg = "您的订单${id}已经确认，请您在$delyTime";
		global $web_root;
		if($delyType == 1)
			$m_msg .= '收货。';
		else
			$m_msg .= '至XX取货。';
		if($pwd != '')
			$m_msg .= "您的网络账号8位密码[$pwd]，欢迎您登录".$web_root['web'];
		$retmsg;
		SendMobileMsg($retmsg, array($mobile), $m_msg);
	}

	private function GetAmount($cart, &$cnt)
	{
		//计算总值
		$amount = 0;
		$cnt = 0;
		$cart = $_SESSION['cart'];
		foreach($cart as $item)
		{
			if($item['status'] == 0)
			{
				$amount += $item['discount'] * $item['price'] * $item['cnt'];
				$cnt++;
			}
		}
		return round($amount, 2);
	}
}

